<?php

namespace app\qsapi\service;

use app\common\controller\AilPay;
use app\common\controller\WxPay;
use app\models\EvtGoods;
use app\qsapi\model\BoxYunGoods;
use app\qsapi\model\BoxYunOrder;
use app\qsapi\model\BoxYunPaymentAccount;
use app\qsapi\model\BoxYunPayType;
use app\service\SdkPayService;
use app\util\Common;
use think\cache\driver\Redis;
use think\Controller;
use think\Db;
use think\Exception;
use think\facade\Log;

class BoxYunPayService extends BaseService
{
    /**
     * 检测订单号是否支付
     */
    public function checkYunOrderPay($param)
    {
        $orderNumber = $param['order_num'];

        $order     = new BoxYunOrder();
        $orderInfo = $order->where(['order_num' => $orderNumber])->find();
        if (empty($orderInfo)) {
            return api_message([], '订单不存在！', 0);
        }

        if (intval($orderInfo['pay_status']) == 1) {
            return api_message([], '订单支付成功');
        } else {
            return api_message([], '订单未支付！', 0);
        }
    }

    /**
     * 支付方式
     */
    public function yunOrderPayType(): array
    {
        $device = $this->platform;
        $where[] = ['status','=', 1];
        if($device != 'pc'){
            $version =  $this->getVersion();
            if($version < '1.4.7'){
                $where[] = ['pay_type','in',['wxpay','alipay']];
            }
        }
        $list = BoxYunPayType::field('id,pay_type,name,icon')->where($where)->select();;

        foreach ($list as &$item) {
            switch ($item['pay_type']) {
                case 'wxpay':
                    $item['type'] = 'redirect';
                    break;
                case 'wxpay_qrcode':
                    $item['type'] = 'code';
                    break;
                case 'alipay':
                    $item['type'] = 'redirect';
                    break;
                case 'alipay_qrcode':
                    $item['type'] = 'code';
                    break;
            }

        }
        return api_message($list ? $list->toArray() : []);
    }

    /**
     * 支付
     */
    public function yunOrderPay($member_id, $param)
    {
        //=======用户防刷操作redis=======
        $redis = new Redis(getRedisConfig());
        if ($redis->get('yun_order_pay:' . $member_id)) {
            return api_message([], '操作过于频繁', 0);
        }
        $redis->set('yun_order_pay:' . $member_id, $member_id, 5);
        //=======用户防刷操作redis==========

        $orderNumber = $param['order_num'];
        $payType     = $param['pay_type'];
        if (empty($orderNumber) || empty($payType)) {
            return api_message([], '缺少参数！', 0);
        }

        $order     = new BoxYunOrder();
        $orderInfo = $order->where(['order_num' => $orderNumber])->find();
        if (empty($orderInfo)) {
            return api_message([], '订单不存在！', 0);
        }
        if (intval($orderInfo['pay_status']) == 1) {
            return api_message([], '订单已支付！', 0);
        }

        $goodInfo                = BoxYunGoods::where(['id' => $orderInfo['goods_id']])->find();
        $orderInfo['goods_name'] = $goodInfo['name'];

        $url                = \request()->domain();
        $payment_id         = BoxYunPayType::where('pay_type', $payType)->value('payment_id');
        $paymentAccountData = BoxYunPaymentAccount::where('id', $payment_id)->find();
        $payConfig          = json_decode($paymentAccountData['params'], true);

        if (!empty($payConfig)) {
            if ($payType == 'wxpay') {
                $payHost                 = empty($paymentAccountData['host']) ? $url : $paymentAccountData['host'];
                $orderInfo['notify_url'] = $payHost . '/BoxYunNotify/wxNotify';

                $WxPay          = new WxPay();
                $payUrl         = $WxPay->toYunPay($orderInfo, $payConfig);
                $payRedirectUrl = $payHost . '/WeixinPay/weixinform?order_num=' . $orderNumber . '&pay_url=' . base64_encode($payUrl . "&redirect_url=" . urlencode($payHost . "/WeixinPay/paysuccess?order_num=" . $orderNumber . '&pay_url=' . base64_encode($payUrl)));
                return api_message($payRedirectUrl, '操作成功');
            } else if ($payType == 'alipay') {
                $orderInfo['notify_url'] = $url . '/BoxYunNotify/aliNotify';
                $orderInfo['return_url'] = '';
                $orderInfo['quit_url']   = $url . '/AliPay/paysuccess';
                $AliPay                  = new AilPay();
                $payUrl                  = $AliPay->toYunPay($orderInfo, $payConfig, 'wap');
                return api_message($payUrl, '操作成功');
            }else if ($payType == 'wxpay_qrcode') {
                $payHost                 = empty($paymentAccountData['host']) ? $url : $paymentAccountData['host'];
                $orderInfo['notify_url'] = $payHost . '/BoxYunNotify/wxNotify';

                $WxPay  = new WxPay();
                $payUrl = $WxPay->toYunCodePay($orderInfo, $payConfig);
                $this->getQrCode($payUrl);
            }else if ($payType == 'alipay_qrcode') {
                $payUrl = $url . '/BoxYunPay/aliCodePay?order_num=' . $orderNumber;
                $this->getQrCode($payUrl);
            }
        }else{
            return api_message([], '请用支付宝或者微信支付！', 0);
        }
    }

    public function getQrCode($url)
    {
        $url = urldecode($url);
        require_once VENDOR_PATH . 'phpqrcode.php';
        $errorCorrectionLevel = intval(3);//容错级别
        $matrixPointSize      = intval(4);//生成图片大小
        //生成二维码图片
        echo $_SERVER['REQUEST_URI'];
        ob_clean();
        $object = new \QRcode();
        echo $object->png($url, false, $errorCorrectionLevel, $matrixPointSize, 2);
    }


    /**
     * Desc : 支付宝扫码支付
     * User : Steven
     * Date : 2024-10-12 15:18
     * @return array|void
     */
    public function aliCodePay()
    {
        $param       = request()->param();
        $orderNumber = $param['order_num'];

        $order     = new BoxYunOrder();
        $orderInfo = $order->where(['order_num' => $orderNumber])->find();
        if (empty($orderInfo)) {
            return message("订单不存在", false);
        }
        if (intval($orderInfo['pay_status']) == 1) {
            return message("订单已支付", false);
        }

        $goodInfo                = BoxYunGoods::where(['id' => $orderInfo['goods_id']])->find();
        $orderInfo['goods_name'] = $goodInfo['name'];

        $payment_id               = BoxYunPayType::where('pay_type', 'alipay_qrcode')->value('payment_id');
        $paymentAccountData       = BoxYunPaymentAccount::where('id', $payment_id)->find();
        $payConfig                = json_decode($paymentAccountData['params'], true);
        $url                      = \request()->domain();
        $timeExpire               = date("Y-m-d H:i:s", strtotime($orderInfo['create_time']) + 15 * 60 - 5);
        $orderInfo['time_expire'] = $timeExpire;
        $orderInfo['notify_url']  = $url . '/BoxYunNotify/aliNotify';
        $orderInfo['return_url']  = '';
        $orderInfo['quit_url']    = $url . '/AliPay/paysuccess';
        $AliPay                   = new AilPay();
        $payUrl                   = $AliPay->toYunPay($orderInfo, $payConfig, 'wap');
        header("Location:" . $payUrl);
    }

    /**
     * Desc : 微信扫码支付
     * User : Steven
     * Date : 2024-10-12 15:18
     * @return mixed
     */
    public function wxCodePay()
    {
        $data = $_POST;
        $WxPay = new WxPay();
        $order     = new BoxYunOrder();
        $orderInfo = $order->where(['order_num' => $data['pay_order_number']])->find();
        $url = \request()->domain();
        $orderInfo['notify_url'] = $url.'/BoxRechargeNotify/wxNotify';

        $info               = BoxRechargeConfig::where(['id' => $orderInfo['config_id']])->find();
        $orderInfo['title'] = $info['title'];

        $payment_id              = BoxYunPayType::where('pay_type', 'wxpay_qrcode')->value('payment_id');
        $paymentAccountData      = BoxYunPaymentAccount::where('id', $payment_id)->find();
        $payConfig               = json_decode($paymentAccountData['params'], true);

        $res = $WxPay->yunJsApiPay($orderInfo,$data['openid'],$payConfig);
        return json_decode($res,true);
    }

}
